# Scenario : decode Vorbis files to Wave PCM
# Copyright 2007-2011, Sylvain Rougeaux (Cyber Sinh), www.luminescence-software.org
# Version 2.3 (2011-09-24)

#################################################################
$source = "%SOURCE%\*"
$recursive = %RECURSIVE%
$output_file = "%OUTPUT_FILENAME_PATTERN%"
$output_folder = "%OUTPUT_FOLDER_PATTERN%"
$shutdown = %SHUTDOWN%
$hibernate = %HIBERNATE%
#################################################################

Clear-Host

$bin = Split-Path $MyInvocation.MyCommand.Definition -Parent

[Reflection.Assembly]::LoadFrom("$bin\Functions.dll") | Out-Null
[Reflection.Assembly]::LoadFrom("$bin\Luminescence.Xiph.dll") | Out-Null

$oggdec = "$bin\Encoders\Generic\oggdec.exe"

if ($recursive) { $files = Get-ChildItem $source -Include *.ogg -Recurse }
else { $files = Get-ChildItem $source -Include *.ogg }

if ($files -eq $null)
{
 Write-Host "There is no file to process."
 exit
}

if ($files.GetType().Name -eq "FileInfo") { $count = 1 }
else { $count = $files.Length }

$i = 0

foreach ($file in $files)
{
   $i++
   Write-Progress -Activity "Decoding Vorbis files to Wave PCM ($i / $count)..." -Status "$file" -PercentComplete ($i / $count * 100)

   $audio = New-Object -TypeName Luminescence.Xiph.OggTagger -ArgumentList $file
   if ($audio.Codec -ne [Luminescence.Xiph.OggCodec]::Vorbis) { continue }
   
   if (![String]::IsNullOrEmpty($output_folder))
   {
      $folder = [XiphMediaEncoder.TagProcessor]::PathFromTags($output_folder, $audio.GetAllTags())
      if (![System.IO.Directory]::Exists($folder)) { [System.IO.Directory]::CreateDirectory($folder) | Out-Null }
   }
   else
   {
      $folder = [System.IO.Path]::GetDirectoryName($file)
   }
  
   $filename = [System.IO.Path]::GetFileNameWithoutExtension($file) + ".wav"
   if (![String]::IsNullOrEmpty($output_file))
   {
      $buffer = [XiphMediaEncoder.TagProcessor]::FileNameFromTags($output_file, $audio.GetAllTags())
      if ($buffer -ne $null) { $filename = $buffer + ".wav" }
   }
   
   $output = [System.IO.Path]::Combine($folder, $filename)

   $startInfo = New-Object -TypeName Diagnostics.ProcessStartInfo
   $startInfo.FileName = $oggdec
   $startInfo.Arguments="--quiet --output ""$output"" ""$file"""
   $startInfo.UseShellExecute = $false
   $startInfo.RedirectStandardOutput = $true
   
   $proc = [System.Diagnostics.Process]::Start($startInfo)
   $proc.WaitForExit()
}

Write-Host "Decoding completes."

if ($shutdown) 
{ 
    shutdown /s /t 3
    exit 
}

if ($hibernate) 
{ 
    shutdown /h /t 3 
    exit
}